<?php
/***
 * 请求的Trait
 * Date: 2021/1/5
 * Time: 11:46 上午
 * Author gan
 */
declare(strict_types=1);

namespace RX\Traits;

use EasySwoole\Http\Request;
use EasySwoole\Utility\Str;
use RX\Enums\CommonEnum;
use RX\Exception\BizException;

trait RequestTrait
{
    /**
     * @Author: gan
     * @Description: 获取请求内容
     * @Version: 1.0.0
     * @Date: 2021/12/23 3:03 下午
     * @param Request $request
     * @return array
     * @throws BizException
     */
    public function getRequestParams(Request $request): array
    {
        $method = strtoupper($request->getMethod());
        if ($method == 'GET') {
            return $request->getQueryParams();
        }

        $headers = $request->getHeader('content-type');
        if ($headers && Str::contains($headers[0], ['json', 'application/json'])) {
            $data = $request->getSwooleRequest()->rawContent();
            try {
                $data = json_decode($data, true);
            } catch (\Throwable $e) {
                throw new BizException(CommonEnum::class, CommonEnum::INVALID_PARAMS);
            }
        } else {
            $data = $request->getParsedBody();
        }

        if (empty($data) || !is_array($data)) {
            return [];
        }

        return $data;
    }


    /**
     * 获取客户端真实IP
     *
     * @param Request $request
     * @return array|mixed|string|string[]
     * Date: 2021/1/5
     * Time: 11:48 上午
     * Author: gan
     */
    public function getClientIp(Request $request)
    {
        $ip = $request->getHeader('x-real-ip');
        if (empty($ip)) {
            $ip = $request->getHeader('remote-addr');
        }
        if (empty($ip)) {
            $ip = $request->getHeader('remote-ip');
        }
        if (empty($ip)) {
            $ip = $request->getSwooleRequest()->server['remote_addr'];
        }
        if (is_array($ip)) {
            return $ip[0];
        }
        return $ip;
    }
}
